/**
 * 
 */
package com.xinghou.platform.file.handler.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.chain.impl.ContextBase;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.xinghou.platform.file.chain.impl.PhotoUploadChain;
import com.xinghou.platform.file.handler.BaseHandler;
import com.xinghou.platform.file.model.ResourceContext;
import com.xinghou.platform.util.ConfigUtil;
import com.xinghou.platform.util.JsonUtil;

/**
 * @author wxtdy
 *
 */
@Service
public class PhotoUploadHandler implements BaseHandler {
	
	@Resource
	private PhotoUploadChain photoChain;

	@Override
	public void execute(ContextBase context) throws Exception {
		@SuppressWarnings("unchecked")
		ResourceContext<byte[], String> resourceContext = (ResourceContext<byte[], String>)context;
		resourceContext.getResponse().setResultCode(0);
		photoChain.execute(context);
		
		if(resourceContext.getResponse().getResultCode() == 0){
			
			Map<String, String> result = new HashMap<String, String>();
			result.put("resource_type", resourceContext.getRequest().getResourceType().toString());
			result.put("resource_id", resourceContext.getSource().getResourceId());
			result.put("thumbnails_id", resourceContext.getExtars()[0].getResourceId());
			result.put("download_url", ConfigUtil.getProperty("local_domain") 
					+ "/resource_type/"
					+ resourceContext.getRequest().getResourceType().toString()
					+ "/resource_id/"
					+ resourceContext.getSource().getResourceId());
			result.put("thumbnails_url", ConfigUtil.getProperty("local_domain") 
					+ "/resource_type/"
					+ resourceContext.getRequest().getResourceType().toString()
					+ "/resource_id/"
					+ resourceContext.getExtars()[0].getResourceId());
						
			resourceContext.getResponse().setBody(JsonUtil.toJson(result));
			resourceContext.getResponse().getResponseHeaders().set("ContentType", "application/json;charset=UTF-8");
			resourceContext.getResponse().setStatusCode(HttpStatus.OK);
		}else if(resourceContext.getResponse().getResultCode() > 0){
			resourceContext.getResponse().getResponseHeaders().set("ContentType", "application/json;charset=UTF-8");
			resourceContext.getResponse().setStatusCode(HttpStatus.OK);
		}else{
			resourceContext.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		}
		
		
	}

	/**
	 * @param photoChain the photoChain to set
	 */
	public void setCrebitChain(PhotoUploadChain photoChain) {
		this.photoChain = photoChain;
	}

}
